<template>
  <!--  1.使用说明：该组件默认为父盒子宽高的100%
      2.插槽父组件中传入，传过来的内容最好有div容器包裹 
      3.policy为获取验证的上传路径，由父组件中传值过来
      4.type --- 1,图片.2,ipa.3,apk
      5.module ---realname:实名认证,ipa:ipa文件,apk:apk文件。
 -->
  <div>
    <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false"
      :on-change="handleAvatarChange" :auto-upload="false" drag>
      <!-- on-change为事件入口，
        type区分身份证和企业执照
        
     -->
      <!-- 插槽父组件中传入，传过来的内容最好有div容器包裹 -->
      <slot></slot>
    </el-upload>
    <!-- 测试父组件中的值是否传入进来 -->
    <!-- <div>{{ policy }}</div> -->
  </div>
</template>
<script>
  /* eslint-disable */
  // import axios from "axios";
  export default {
    // policy为获取验证的上传路径，由父组件中传值过来
    // type --- 1,图片.2,ipa.3,apk,4,mobileconfig
    // module ---realname:实名认证,ipa:ipa文件,apk:apk文件,config:mobileconfig文件
    props: {
      type: [String, Number],
      module: String,
      progress: Function,
      beforeupload: Function, //开始上传前调用
      change: Function, //文件开始上传调用
      success: Function, //文件上传成功调用
      error: Function,
      rzstatus: [String, Number] //该参数用来验证是否实名制
    },
    data() {
      return {
        signature: {}
      };
    },

    methods: {
      // 上传文件的状态发生了改变执行该函数
      handleAvatarChange(file) {
        console.log(file);
        var istodown = this.beforeupload(file)
        console.log(istodown);
        if (this.beforeupload(file)) {
          var that = this
          that.beforeupload(file);
          console.log(2);
          console.log(that.type);
          console.log(that.rzstatus);
          that.$nextTick(function () {
            console.log(that.type, that.module, that.rzstatus);
            if (that.type != "1") {
              console.log(that.rzstatus);
              console.log('开始上传');
              that.change(file);
            } else {
              that.change(file);
            }
          });
          that.$nextTick(function () {
            // console.log(123);
            that.postImage(file.raw);
          });
        }
      },

      async getStsToken() {
        //验证返回 signature 失效时间
        let now = new Date().getTime() / 1000;
        var params = new FormData();
        params.append("type", this.type);
        params.append("module", this.module);
        const expire = (this.signature.data && this.signature.data.expire) || 0;
        // 当前时间 + 3s 缓存 小于 过期时间 则 不用重新获取
        if (now + 3 < expire) return this.signature;
        else this.signature = await this.$post(this.API.getpolicy, params);
        console.log(this.signature);
        return this.signature;
      },
      // 该函数被handleAvatarSuccess调用
      postImage(file) {
        this.getStsToken().then(data => {
          if (data) {
            let name = data.file_name;
            let obj = {
              host: data["host"],
              policy: data["policy"],
              OSSAccessKeyId: data["accessid"],
              signature: data["signature"],
              expire: parseInt(data["expire"]),
              callbackbody: data["callback"],
              key: `${data["dir"]}${name}`,
              success_action_status: "200",
              name
            };
            console.log(obj);
            const that = this;
            async function post() {
              try {
                const config = {
                  onUploadProgress: that.progress
                };
                var params = new FormData();
                params = new FormData();
                Object.keys(obj).forEach(k => params.append(k, obj[k]));
                params.append("file", file);
                let upUrl = String(obj.host + "/" + obj.key).trim();
                that.$post(`${data["host"]}`, params, config).then(res => {
                  console.log(res);
                  if (res != "") {
                    that.error(upUrl);
                    return false;
                  } else {
                    if (that.type == 1) {
                      that.success(upUrl);
                    } else {
                      that.success(upUrl);
                    }
                    console.log("上传成功");
                  }
                });
              } catch (e) {
                console.log(e);
              }
            }
            post();
          } else {
            this.msgError("ERROR");
          }
        });
      }
    }
  };

</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    display: flex !important;
    align-items: center;
    justify-content: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  div>>>.el-upload-dragger {
    width: auto !important;
    height: auto !important;
    border: none !important;
  }

</style>
